//fetch 请求
//加密方法
import {encrypt}            from './encrypt';
import {requestUrl}         from './config'
import qs                   from "qs"
import { Toast } from 'vant'
export async function $httpFetch(data={},flag=false,type='POST'){
    if(!window.fetch){
        return Promise.reject('浏览器不支持fetch');
    }
    data=tips(data,flag)
    let requestConfig={
      method:type,
      headers:type !== 'UPLOAD' ? {} : {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      mode: "cors",//跨域
    };
    if(type.toUpperCase()==='POST'){
        Object.defineProperties(requestConfig, {
            'body':{
                value:qs.stringify(data)
            }
        })
    }
    if(type.toUpperCase()==='GET'){
        let dataStr = '';
        Object.keys(data).forEach(key => {
         dataStr = dataStr + key + '=' + data[key] + '&';
        })
        if(dataStr)
        url=url+'?'+dataStr
    }
    try {
        let response = await fetch(requestUrl.trim(), requestConfig);
        response = await processResult(response)
        Toast.clear()
        return response
    } catch (error) {
        console.log(error)
        Toast.clear()
        if(typeof error==='object'){
            error='请求失败'
        }
        Toast({message:error,duration:1000});
        return Promise.reject(error);
    }
}

export async function $upload(method, avatar){
    let data = {method};
    data.sign = encrypt(data);
    let data2 = new FormData();
    for(let i in data){
        data2.append(i, data[i]);
    }
    data2.append('avatar', avatar);
    let response = await fetch(requestUrl.trim(), {
        method: 'POST',
        body: data2,
    });
    response = await processResult(response)
    return response;
}

function tips(data,flag){
    data.sign = encrypt(data)
    if (!flag) {
        Toast.loading('加载中')
    }
    return data
}
//处理结果
async function processResult(response) {
    let _response = checkStatus(response)
    _response = await parseResult(_response);
    return _response;
}
function checkStatus(response) {//检查响应状态
    if(response.status >= 200 && response.status < 300) {//响应成功
        return response;
    }
    if(response.status === 301 || response.status === 302) {//重定向
        window.location = response.headers.get('Location');
    }
    const error = new Error(response);
    error.data = response;
    throw error;
}
async function parseResult(response) {//解析返回的结果
    const contentType = response.headers.get('Content-Type');
    if(contentType != null) {
        if(contentType.indexOf('text') > -1) {
            return await response.text()
        }
        if(contentType.indexOf('form') > -1) {
            return await response.formData();
        }
        if(contentType.indexOf('video') > -1) {
            return await response.blob();
        }
        if(contentType.indexOf('json') > -1) {
            const data=await response.json();
            // return data
            switch(Number(data.errorCode)){
                case 200:return data;break;
                case 403:return location.href='/#/login';break;
                default:return Promise.reject(data.message);
            }
        }
    }
    return await response.text();
}
